package com.github.postsanf.yinian.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.AdviceActivity;
import com.github.postsanf.yinian.activity.AwardActivity;
import com.github.postsanf.yinian.activity.CouponListActivity;
import com.github.postsanf.yinian.activity.GuideImportActivity;
import com.github.postsanf.yinian.activity.NewsActivity;
import com.github.postsanf.yinian.activity.OrderListActivity;
import com.github.postsanf.yinian.activity.ProfileActivity;
import com.github.postsanf.yinian.activity.SettingActivity;
import com.github.postsanf.yinian.activity.UserStatusActivity;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.bean.YNUserData;
import com.github.postsanf.yinian.bean.YNUserStorageAward;
import com.github.postsanf.yinian.bean.YNUserStoragePlace;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNGetUserResponse;
import com.github.postsanf.yinian.entity.YNLoginResponse;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class MyFragmnet extends BaseFragment implements View.OnClickListener {
    private View view;
    private WrapContentLinearLayoutManager mLinearLayoutManager;
    private SimpleDraweeView mUserStatusBG;
    private SimpleDraweeView iv_user_status_avatar;
    private TextView tv_user_status_nickname;
    private TextView tv_user_status_msg;
    public static String avatarPic;
    public static String nickname;
    private RelativeLayout rl_mymemory;
    //    private RelativeLayout rl_lock;
    private RelativeLayout rl_myspace;
    private RelativeLayout rl_import;
    private RelativeLayout rl_setting;
    private RelativeLayout rl_news;
    private ImageView iv_space;
    private ImageView iv_news_point;
    private TextView titlt_top;
    private SimpleDraweeView preview_first;
    private SimpleDraweeView preview_second;
    private SimpleDraweeView preview_third;
    private SimpleDraweeView iv_user_status_album_top;
    private TextView tv_space;
    private ImageView iv_top_setting;
    private RelativeLayout rl_order;
    private RelativeLayout rl_advice;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_my, null);
//        init();                 // 准备工作
        initView();             // 初始化界面
        return view;
    }

//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        ViewTreeObserver observer = rl_myspace.getViewTreeObserver();
//        observer .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                rl_myspace.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//                final int w = rl_myspace.getMeasuredWidth();
//                final int h = rl_myspace.getMeasuredHeight();
//                Log.i("xjs","onGlobalLayout=hhhh==>"+h);
//            }
//        });
//    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
//        Log.d("yuhao","onCreateView");
        registerBoradcastReceiver();
        boolean getSpace = SpUtils.getBoolean(getActivity(), "getSpace");
        if (getSpace) {
            iv_space.setVisibility(View.VISIBLE);
        } else {
            iv_space.setVisibility(View.GONE);
        }
        super.onActivityCreated(savedInstanceState);
    }

    // 注册接收者
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.Avatar);
        myIntentFilter.addAction(ACTIONs.actionAlertMeBg);
        myIntentFilter.addAction(ACTIONs.actionMymessageNums);
        myIntentFilter.addAction(ACTIONs.actionAlbumInit);
        myIntentFilter.addAction(ACTIONs.actionDeleteList);
        myIntentFilter.addAction(ACTIONs.network);
        getActivity().registerReceiver(avatarReceiver, myIntentFilter);
    }

    BroadcastReceiver avatarReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.Avatar:
                    String avatarUri = intent.getStringExtra("avatarUri");
                    ImageOptHelper.showFrescoNative(Uri.parse("file://" + avatarUri), iv_user_status_avatar, getContext());
                    break;
                case ACTIONs.actionAlertMeBg:
//                    Log.d("yuhao", "actionAlertMeBg");
//                    String bgPaths2 = YNUrlHelper.getOfficialUrl(getContext(), application.getCurUser().getUbackground());
//                    Uri bgUri2 = Uri.parse(bgPaths2);
//                    Uri bgUri = Uri.parse(YNUrlHelper.getStatusBlur(getContext(), bgPaths2));
//                    ImageOptHelper.showFrescoAvatar(bgUri, iv_user_status_album_top, getContext());
                    getUserTop(application.getCurID(), true);
                    break;
                case ACTIONs.actionMymessageNums:
                    SharedPreferences preferences = context.getSharedPreferences(
                            ACTIONs.mymsg, 0);
                    boolean invitebb = preferences.getBoolean(ACTIONs.invitebb, false);
                    boolean commentbb = preferences.getBoolean(ACTIONs.commentbb, false);
                    boolean notifybb = preferences.getBoolean(ACTIONs.notifybb, false);
                    int invitenum = preferences.getInt(ACTIONs.invitenum, 0);
                    int commentnum = preferences.getInt(ACTIONs.commentnum, 0);
                    int notifynum = preferences.getInt(ACTIONs.notifynum, 0);
                    int totalnum = invitenum + commentnum + notifynum;
                    if (invitebb || commentbb || notifybb) {
//                        rb_my_news.setVisibility(View.VISIBLE);
                        iv_news_point.setVisibility(View.VISIBLE);
                    } else {
                        iv_news_point.setVisibility(View.GONE);
                    }
                    initIsAward();
                    break;
                case ACTIONs.actionAlbumInit:
                    getUserData(application.getCurID());
                    break;
                case ACTIONs.actionDeleteList:
//                    Log.d("yuhao", "actionDeleteList: ");
                    initGetSpace();
                    break;
                case ACTIONs.network:
                    init();                 // 准备工作
                    break;
            }
        }
    };

    // 获取成员动态
    private void getUserStatus(int userid, int loadId) {
        String urlAddress;
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        urlAddress = getString(R.string.ynShowMeInfo);
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        mParam.put(CommonConstants.YNS_MIN_ID, String.valueOf(loadId));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + urlAddress)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resUserStatus = gson.fromJson(s, YNStatusResponse.class);
                        if (resUserStatus != null && ReqUtils.isSuccess(resUserStatus.getCode())) {
                            // 清空状态列表并更新
                            List<YNStatus> statusLists = new ArrayList<>();
                            statusLists.addAll(resUserStatus.getData());
                            List<String> urlList = new ArrayList<>();
                            for (int i = 0; i < statusLists.size(); i++) {
                                for (int j = 0; j < statusLists.get(i).getThumbnail().size(); j++) {
                                    urlList.add(statusLists.get(i).getThumbnail().get(j));

                                    if (urlList.size() >= 3) {
                                        break;
                                    }
                                }
                            }
//                            Log.d("yuhao", "urlList="+urlList.size());
                            if (urlList.size() >= 3) {
                                ImageOptHelper.showFrescoStatus(Uri.parse(urlList.get(0)), preview_first, getActivity());
                                ImageOptHelper.showFrescoStatus(Uri.parse(urlList.get(1)), preview_second, getActivity());
                                ImageOptHelper.showFrescoStatus(Uri.parse(urlList.get(2)), preview_third, getActivity());
                            } else if (urlList.size() == 2) {
                                ImageOptHelper.showFrescoStatus(Uri.parse(urlList.get(0)), preview_first, getActivity());
                                ImageOptHelper.showFrescoStatus(Uri.parse(urlList.get(1)), preview_second, getActivity());
                            } else if (urlList.size() == 1) {
                                ImageOptHelper.showFrescoStatus(Uri.parse(urlList.get(0)), preview_first, getActivity());
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void init() {
        getUserTop(application.getCurID(), false);
        getUserData(application.getCurID());
        getUserStatus(application.getCurID(), 0);
        initGetSpace();
    }

    private void initView() {
        tv_user_status_msg = (TextView) view.findViewById(R.id.tv_user_status_msg);
        tv_user_status_msg.setVisibility(View.VISIBLE);
        mUserStatusBG = (SimpleDraweeView) view.findViewById(R.id.iv_user_status_album_top);
        iv_user_status_avatar = (SimpleDraweeView) view.findViewById(R.id.iv_user_status_avatar);
        iv_user_status_album_top = ((SimpleDraweeView) view.findViewById(R.id.iv_user_status_album_top));
        tv_user_status_nickname = (TextView) view.findViewById(R.id.tv_user_status_nickname);
        iv_space = ((ImageView) view.findViewById(R.id.iv_space));
        mLinearLayoutManager = new WrapContentLinearLayoutManager(getContext());
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rl_news = ((RelativeLayout) view.findViewById(R.id.rl_news));
        rl_mymemory = ((RelativeLayout) view.findViewById(R.id.rl_mymemory));
//        rl_lock = ((RelativeLayout) view.findViewById(R.id.rl_lock));
        rl_myspace = ((RelativeLayout) view.findViewById(R.id.rl_myspace));
        rl_import = ((RelativeLayout) view.findViewById(R.id.rl_import));
        rl_setting = ((RelativeLayout) view.findViewById(R.id.rl_setting));
        iv_news_point = ((ImageView) view.findViewById(R.id.iv_news_point));
        titlt_top = ((TextView) view.findViewById(R.id.titlt_top));
        preview_first = ((SimpleDraweeView) view.findViewById(R.id.preview_first));
        preview_second = ((SimpleDraweeView) view.findViewById(R.id.preview_second));
        preview_third = (SimpleDraweeView) view.findViewById(R.id.preview_third);
        tv_space = ((TextView) view.findViewById(R.id.tv_space));
        iv_top_setting = ((ImageView) view.findViewById(R.id.iv_top_setting));
        rl_order = ((RelativeLayout) view.findViewById(R.id.rl_order));
        rl_advice = ((RelativeLayout) view.findViewById(R.id.rl_advice));
        titlt_top.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fzqk.ttf"));
        titlt_top.setText("我的");
        view.findViewById(R.id.rl_coupon).setOnClickListener(this);
        rl_news.setOnClickListener(this);
        rl_mymemory.setOnClickListener(this);
//        rl_lock.setOnClickListener(this);
        rl_myspace.setOnClickListener(this);
        rl_import.setOnClickListener(this);
        rl_setting.setOnClickListener(this);
        iv_top_setting.setOnClickListener(this);
        rl_order.setOnClickListener(this);
        rl_advice.setOnClickListener(this);
        iv_user_status_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent2Activity(ProfileActivity.class);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_coupon:
                intent2Activity(CouponListActivity.class);
                break;
            case R.id.rl_news:
                intent2Activity(NewsActivity.class);
                Intent statintentbtnews = new Intent(ACTIONs.record);
                statintentbtnews.putExtra("key", "消息中心_4");
                statintentbtnews.putExtra("value", 1);
                getActivity().sendBroadcast(statintentbtnews);
                break;
            case R.id.rl_mymemory:
                Intent intent = new Intent(getContext(), UserStatusActivity.class);
//                application.setCurGid(0);
                intent.putExtra(CommonConstants.YNUSERID, application.getCurID());
                intent.putExtra(CommonConstants.YNISME, true);
                startActivity(intent);
                Intent statintentbtmemory = new Intent(ACTIONs.record);
                statintentbtmemory.putExtra("key", "我的回忆_4");
                statintentbtmemory.putExtra("value", 1);
                getActivity().sendBroadcast(statintentbtmemory);
                break;
//            case R.id.rl_lock:
//                intent2Activity(MMLockActivity.class);
//                break;
            case R.id.rl_myspace:
                intent2Activity(AwardActivity.class);
                Intent statintentbtspace = new Intent(ACTIONs.record);
                statintentbtspace.putExtra("key", "我的空间_4");
                statintentbtspace.putExtra("value", 1);
                getActivity().sendBroadcast(statintentbtspace);
                break;
            case R.id.rl_import:
                intent2Activity(GuideImportActivity.class);
//                intent2Activity(LocalBackUpActivity.class);
//                Intent statintentbtimport = new Intent(ACTIONs.record);
//                statintentbtimport.putExtra("key", "私人相册_4");
//                statintentbtimport.putExtra("value", 1);
//                getActivity().sendBroadcast(statintentbtimport);
                break;
//            case R.id.rl_setting:
//                intent2Activity(SettingActivity.class);
//                break;
            case R.id.iv_top_setting:
                intent2Activity(SettingActivity.class);
                break;
            case R.id.rl_order:
                intent2Activity(OrderListActivity.class);
                break;
            case R.id.rl_advice:
                intent2Activity(AdviceActivity.class);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
        getContext().unregisterReceiver(avatarReceiver);
    }


    // 获取成员头信息
    private void getUserTop(int userid, final boolean modify) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNLoginResponse resUser = gson.fromJson(s, YNLoginResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            YNUser user = resUser.getData().get(0);
                            Uri bgUri = Uri.parse(YNUrlHelper.getStatusBlur(getContext(), user.getUbackground()));
                            ImageOptHelper.showFrescoAvatar(bgUri, mUserStatusBG, getContext());
                            if (!modify) {
                                avatarPic = user.getUpic();
                                nickname = user.getUnickname();
                                Uri avatarUri = Uri.parse(YNUrlHelper.getAvatarUrl(getContext(), user.getUpic()));
                                ImageOptHelper.showFrescoAvatar(avatarUri, iv_user_status_avatar, getContext());
                                tv_user_status_nickname.setText(user.getUnickname());
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void getUserData(int userid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.GetUserData))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNGetUserResponse resUser = gson.fromJson(s, YNGetUserResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            YNUserData ynUserData = resUser.getData().get(0);
                            String album = "0";
                            String photo = "0";
                            String event = "0";
                            if (ynUserData.getAlbum() != null && !ynUserData.getAlbum().equals("")) {
                                album = ynUserData.getAlbum();
                            }
                            if (ynUserData.getPhoto() != null && !ynUserData.getPhoto().equals("")) {
                                photo = ynUserData.getPhoto();
                            }
                            if (ynUserData.getEvent() != null && !ynUserData.getEvent().equals("")) {
                                event = ynUserData.getEvent();
                            }
                            tv_user_status_msg.setText("已加入" + album + "个圈子," + photo + "个瞬间," + event + "个时刻");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    //获取我的空间和已使用空间
    private void initGetSpace() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUserData))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUserStoragePlace userStoragePlace = gson.fromJson(s, YNUserStoragePlace.class);
                        if (userStoragePlace.getData().size() != 0) {
                            double totalSpaceToGB = getSpaceToGB(userStoragePlace.getData().get(0).getUtotalspace());
                            double useSpaceToGB = getSpaceToGB(userStoragePlace.getData().get(0).getUusespace());
                            DecimalFormat totalFormat = new DecimalFormat("####.0");//四舍五入不保留小数
                            String showTotal = totalFormat.format(totalSpaceToGB);
                            DecimalFormat useFormat = new DecimalFormat("###0.00");//四舍五入不保留小数
                            String showUse = useFormat.format(useSpaceToGB);
                            tv_space.setText(showUse + "/" + showTotal + "G");
                        }
                        super.onSuccess(s, response);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private double getSpaceToGB(double totalSpace) {
        double totalSpcaeGB = totalSpace / 1024 / 1024;
        return totalSpcaeGB;
    }

    private void initIsAward() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/yinian/UserStoragePlaceCondition")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUserStorageAward storageAward = gson.fromJson(s, YNUserStorageAward.class);
                        if (storageAward.getData().size() != 0) {
                            int uInviteReward = storageAward.getData().get(0).getUInviteReward();
                            int uCreateReward = storageAward.getData().get(0).getUCreateReward();
                            int uJoinReward = storageAward.getData().get(0).getUJoinReward();
                            if (uInviteReward == 2 || uCreateReward == 2 || uJoinReward == 2) {
                                iv_space.setVisibility(View.VISIBLE);
                            } else {
                                iv_space.setVisibility(View.GONE);
                            }
                        }
                        super.onSuccess(s, response);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(getContext());
//        initIsAward();
        initGetSpace();
        boolean message = SpUtils.getBoolean(getActivity(), "message");
        if (message) {
            iv_news_point.setVisibility(View.VISIBLE);
        } else {
            iv_news_point.setVisibility(View.GONE);
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(getContext());
    }
}
